import axios from 'axios';

const API_BASE_URL = 'http://localhost:8081/api';

const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export interface AuthResponse {
  status: number;
  data?: any;
  error?: string;
}

interface AuthService {
  login: (credentials: { email: string; password: string }) => Promise<AuthResponse>;
  register: (userData: any) => Promise<AuthResponse>;
  guestLogin: () => Promise<AuthResponse>;
}

const authService: AuthService = {
  async login(credentials) {
    try {
      const response = await api.post('/auth/login', credentials);
      if (response.data.token) {
        localStorage.setItem('token', response.data.token);
      }
      return { status: response.status, data: response.data };
    } catch (error) {
      if (axios.isAxiosError(error)) {
        return { status: error.response?.status || 500, error: error.response?.data?.error || '登录失败' };
      }
      return { status: 500, error: '未知错误' };
    }
  },
  async register(userData) {
    try {
      const response = await api.post('/auth/register', userData);
      return { status: response.status, data: response.data };
    } catch (error) {
      if (axios.isAxiosError(error)) {
        return { status: error.response?.status || 500, error: error.response?.data?.error || '注册失败' };
      }
      return { status: 500, error: '未知错误' };
    }
  },
  async guestLogin() {
    try {
      const response = await api.get('/auth/guest-login');
      if (response.data.token) {
        localStorage.setItem('token', response.data.token);
      }
      return { status: response.status, data: response.data };
    } catch (error) {
      if (axios.isAxiosError(error)) {
        return { status: error.response?.status || 500, error: error.response?.data?.error || '访客登录失败' };
      }
      return { status: 500, error: '未知错误' };
    }
  },
};

export const apiService = {
  auth: authService,
};